/**
 * @NApiVersion 2.x
 * @NScriptType MapReduceScript
 */
define(['N/search', 'N/record', 'N/runtime', '../common/moment', '../common/txUtil'], function (search, record, runtime, moment, txUtil) {
    function getInputData() {
        var mySearch = search.create({
            type: 'customrecord_fba_transaction_report',
            columns: [],
            filters: [[['custrecord_tran_type', 'is', 'Erstattung']
                , 'OR', ['custrecord_tran_type', 'is', 'Refund']
                , 'OR', ['custrecord_tran_type', 'is', 'Remboursement']
                , 'OR', ['custrecord_tran_type', 'is', 'Refund_Retrocharge']
                , 'OR', ['custrecord_tran_type', 'is', 'Erstattung durch Rückbuchung']
                , 'OR', ['custrecord_tran_type', 'is', 'Chargeback Refund']
                , 'OR', ['custrecord_tran_type', 'is', 'Reembolso']]
                , 'AND', ['custrecord_return_flag', 'is', 'F']  //标记没有进行退货
                , 'AND', ["formulanumeric: TO_NUMBER({custrecord_tran_total})", "notgreaterthan", "0"]//total金额<0
            ]
        });
        var results = mySearch.run().getRange({
            start: 0,
            end: 20
        });
        var alls = [];
        if (results.length > 0) {
            for (var i = 0; i < results.length; i++) {
                var result = results[i];
                var tmp = {};
                tmp.id = result.id;
                alls[alls.length] = tmp;
            }
        }
        log.debug('alls', JSON.stringify(alls));
        return alls;
    }

    function map(context) {
        log.debug("start||Remaining governance units: ", runtime.getCurrentScript().getRemainingUsage());
        //log.debug('context', context);
        var value = JSON.parse(context.value);
        var txId = value.id;
        var txRecord = record.load({
            type: 'customrecord_fba_transaction_report',
            id: txId
        });
        var tx = {};
        tx.id = txId;
        tx.sku = txRecord.getValue('custrecord_tran_sku');
        tx.orderId = txRecord.getValue('custrecord_tran_order_id');
        tx.quantity = txRecord.getValue('custrecord_tran_quantity');
        tx.marketplace = txRecord.getValue('custrecord_tran_marketplace');
        // tx.productSales = txRecord.getValue('custrecord_tran_product_sales');
        // tx.shippingCredits = txRecord.getValue('custrecord_tran_shipping_credits');
        // tx.giftWrapCredits = txRecord.getValue('custrecord_tran_gift_wrap_credits');
        // tx.promotionalRebates = txRecord.getValue('custrecord_tran_promotional_rebates');
        // tx.salesTaxCollected = txRecord.getValue('custrecord_tran_sales_tax_collected');
        // tx.marketplaceTax = txRecord.getValue('custrecord_tran_marketplace_facilitator');
        // tx.sellingFees = txRecord.getValue('custrecord_tran_selling_fees');
        // tx.fbaFees = txRecord.getValue('custrecord_tran_fba_fees');
        // tx.otherTxFees = txRecord.getValue('custrecord_tran_other_transaction_fees');
        // tx.other = txRecord.getValue('custrecord_tran_other');
        tx.total = txRecord.getValue('custrecord_tran_total');
        tx.datetime = txRecord.getValue('custrecord_tran_datetime');
        tx.transactionType = txRecord.getValue('custrecord_tran_type');
        tx.storeId = txRecord.getValue('custrecord_tran_store_information');
        log.debug('tx', JSON.stringify(tx));
        var returnSearch = search.create({
            type: 'returnauthorization',
            columns: [],
            filters: ['custbody_tx_report', 'is', txId]
        });
        var results = returnSearch.run().getRange({
            start: 0,
            end: 1
        });
        if (results.length > 0) {
            //throw 'ERROR:return authorization exist';
            record.submitFields({
                type: 'customrecord_fba_transaction_report',
                id: tx.id,
                values: {
                    custrecord_return_error_msg: 'ERROR:return authorization exist!' + results[0].id,
                    custrecord_return_flag: true
                }
            });
        } else {
            log.debug('退货单不存在', '创建退货单');
            try {
                createReturnAuthorization(tx);
                record.submitFields({
                    type: 'customrecord_fba_transaction_report',
                    id: tx.id,
                    values: {
                        custrecord_return_flag: true
                    }
                });
            } catch (e) {
                record.submitFields({
                    type: 'customrecord_fba_transaction_report',
                    id: tx.id,
                    values: {
                        custrecord_return_error_msg: JSON.stringify(e),
                        custrecord_return_flag: true
                    }
                });
            }
        }
        log.debug("end||Remaining governance units: ", runtime.getCurrentScript().getRemainingUsage());
    }


    function createReturnAuthorization(tx) {
        var salesOrderSearch = search.create({
            type: search.Type.SALES_ORDER,
            columns: ['status'],
            filters: [['custbody_platform_order_id', 'is', tx.orderId],
                'AND', ['custbody_platform_store', 'is', tx.storeId]]
        });
        var results = salesOrderSearch.run().getRange({
            start: 0,
            end: 1
        });
        if (results.length > 0) {
            var status = results[0].getText('status');
            if (status === 'Pending Approval' || status === 'Pending Fulfillment' ||
                status === 'Pending Billing/Partially Fulfilled' || status === 'Partially Fulfilled') {
                throw'ERROR:so status wrong!' + tx.orderId + ' ' + status;
            }
        } else {
            throw 'ERROR:so not exist!' + tx.orderId;
        }
        var soId = results[0].id;
        var so = record.load({
            type: 'salesorder',
            id: soId
        });
        var customerId = so.getValue('entity');
        //销售单   生成退货授权单
        var returnAuthorizationId, creditMemoId;
        try {
            var returnAuthorization = record.transform({
                fromType: record.Type.SALES_ORDER,
                fromId: soId,
                toType: record.Type.RETURN_AUTHORIZATION,
                isDynamic: true
            });
            returnAuthorization.setValue('orderstatus', 'B');//Pending Receipt
            returnAuthorization.setValue('custbody_tx_report', tx.id);//设置关联tx报表
            //清空item行
            for (var i = 0; i < returnAuthorization.getLineCount('item'); i++) {
                returnAuthorization.removeLine('item', 0);
            }
            //设置item行
            var itemId = txUtil.getNSItemIdBySellerSkuAndStoreId(tx.sku, tx.storeId);
            var total = txUtil.getFormattedAmount(tx.total, tx.marketplace);
            returnAuthorization.selectNewLine('item');
            returnAuthorization.setCurrentSublistValue('item', 'item', itemId);
            returnAuthorization.setCurrentSublistValue('item', 'quantity', tx.quantity);
            returnAuthorization.setCurrentSublistValue('item', 'amount', -total);
            returnAuthorization.commitLine('item');
            returnAuthorizationId = returnAuthorization.save();
            record.submitFields({
                type: 'customrecord_fba_transaction_report',
                id: tx.id,
                values: {
                    custrecord_return_record: returnAuthorizationId
                }
            });
            log.debug('SUCCESS:created return authorization', 'id:' + returnAuthorizationId);
        } catch (e) {
            throw 'ERROR:cant create return authorization!' + JSON.stringify(e);
        }
        //退货授权单  进行收货
        try {
            var itemReceipt = record.transform({
                fromType: record.Type.RETURN_AUTHORIZATION,
                fromId: returnAuthorizationId,
                toType: record.Type.ITEM_RECEIPT,
                isDynamic: true
            });
            var itemReceiptId = itemReceipt.save();
            record.submitFields({
                type: 'customrecord_fba_transaction_report',
                id: tx.id,
                values: {
                    custrecord_return_item_receipt_record: itemReceiptId
                }
            });
            log.debug('SUCCESS:created item receipt', 'id:' + itemReceiptId);
        } catch (e) {
            throw 'ERROR:cant create return item receipt!' + JSON.stringify(e);
        }
        //退货授权单 生成贷项通知单
        try {
            var creditMemo = record.transform({
                fromType: record.Type.RETURN_AUTHORIZATION,
                fromId: returnAuthorizationId,
                toType: record.Type.CREDIT_MEMO,
                isDynamic: true
            });
            creditMemoId = creditMemo.save();
            record.submitFields({
                type: 'customrecord_fba_transaction_report',
                id: tx.id,
                values: {
                    custrecord_return_credit_memo_record: creditMemoId
                }
            });
            log.debug('SUCCESS:created credit memo', 'id:' + creditMemoId);
        } catch (e) {
            throw 'ERROR:cant create return credit memo!' + JSON.stringify(e);
        }
        //贷项通知单  进行退款
        try {
            var customerRefundRecord = record.create({
                type: record.Type.CUSTOMER_REFUND,
                isDynamic: true
            });
            //设置客户
            customerRefundRecord.setValue('customer', customerId);
            //refundRecord.setValue('account', accountId);
            //refundRecord.setValue('aracct', 2442);
            // 设置支付方式   9 	payoneer
            customerRefundRecord.setValue('paymentmethod', 9);
            // apply
            for (var i = 0; i < customerRefundRecord.getLineCount('apply'); i++) {
                var internalId = customerRefundRecord.getSublistValue('apply', 'internalid', i);
                if (Number(internalId) === Number(creditMemoId)) {
                    customerRefundRecord.selectLine('apply', i);
                    customerRefundRecord.setCurrentSublistValue('apply', 'apply', true);
                    customerRefundRecord.commitLine('apply');
                }
            }
            var customerRefundRecordId = customerRefundRecord.save();
            record.submitFields({
                type: 'customrecord_fba_transaction_report',
                id: tx.id,
                values: {
                    custrecord_return_customer_refund_record: customerRefundRecordId
                }
            });
            log.debug('SUCCESS:created customer refund', 'id:' + customerRefundRecordId);
        } catch (e) {
            throw 'ERROR:cant create return customer refund!' + JSON.stringify(e);
        }
    }

    function reduce(context) {
    }

    function summarize(summary) {
    }


    return {
        getInputData: getInputData,
        map: map,
        reduce: reduce,
        summarize: summarize
    };
});